#!/usr/bin/env python3
"""
测试运行脚本
提供便捷的测试执行方式
"""

import os
import sys
import argparse
import subprocess
import time
from datetime import datetime


def run_command(command, description=""):
    """运行命令并处理结果"""
    print(f"\n{'='*50}")
    print(f"执行: {description}")
    print(f"命令: {command}")
    print(f"{'='*50}")
    
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        print("✅ 执行成功")
        if result.stdout:
            print("输出:", result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print("❌ 执行失败")
        print("错误:", e.stderr)
        return False


def install_dependencies():
    """安装项目依赖"""
    print("📦 安装项目依赖...")
    return run_command("pip install -r requirements.txt", "安装Python依赖包")


def check_appium_server():
    """检查Appium服务器状态"""
    print("🔍 检查Appium服务器...")
    return run_command("appium --version", "检查Appium版本")


def start_appium_server():
    """启动Appium服务器"""
    print("🚀 启动Appium服务器...")
    return run_command("appium --base-path /wd/hub", "启动Appium服务器")


def run_smoke_tests(platform="android"):
    """运行冒烟测试"""
    print("🔥 运行冒烟测试...")
    command = f"pytest test_cases/ -m smoke --platform={platform} -v --html=reports/smoke_test_report.html"
    return run_command(command, f"运行{platform}平台冒烟测试")


def run_functional_tests(platform="android"):
    """运行功能测试"""
    print("⚙️ 运行功能测试...")
    command = f"pytest test_cases/ -m functional --platform={platform} -v --html=reports/functional_test_report.html"
    return run_command(command, f"运行{platform}平台功能测试")


def run_ui_tests(platform="android"):
    """运行UI测试"""
    print("🎨 运行UI测试...")
    command = f"pytest test_cases/ -m ui --platform={platform} -v --html=reports/ui_test_report.html"
    return run_command(command, f"运行{platform}平台UI测试")


def run_all_tests(platform="android"):
    """运行所有测试"""
    print("🧪 运行所有测试...")
    command = f"pytest test_cases/ --platform={platform} -v --html=reports/all_tests_report.html --self-contained-html"
    return run_command(command, f"运行{platform}平台所有测试")


def run_parallel_tests(platform="android", workers=2):
    """并行运行测试"""
    print(f"🔄 并行运行测试 (工作进程: {workers})...")
    command = f"pytest test_cases/ --platform={platform} -v -n {workers} --html=reports/parallel_test_report.html"
    return run_command(command, f"并行运行{platform}平台测试")


def generate_allure_report():
    """生成Allure报告"""
    print("📊 生成Allure报告...")
    command = "allure generate reports/allure-results -o reports/allure-report --clean"
    return run_command(command, "生成Allure测试报告")


def open_allure_report():
    """打开Allure报告"""
    print("🌐 打开Allure报告...")
    command = "allure open reports/allure-report"
    return run_command(command, "打开Allure报告")


def clean_reports():
    """清理报告目录"""
    print("🧹 清理报告目录...")
    import shutil
    try:
        if os.path.exists("reports"):
            shutil.rmtree("reports")
        os.makedirs("reports", exist_ok=True)
        print("✅ 报告目录清理完成")
        return True
    except Exception as e:
        print(f"❌ 清理失败: {e}")
        return False


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="APP自动化测试运行器")
    parser.add_argument("--action", choices=[
        "install", "check", "start-server", "smoke", "functional", "ui", 
        "all", "parallel", "allure", "open-report", "clean"
    ], default="all", help="执行的操作")
    parser.add_argument("--platform", choices=["android", "ios"], default="android", help="测试平台")
    parser.add_argument("--workers", type=int, default=2, help="并行测试的工作进程数")
    parser.add_argument("--device", help="设备名称或ID")
    parser.add_argument("--app-path", help="应用文件路径")
    
    args = parser.parse_args()
    
    print("🚀 APP自动化测试框架")
    print(f"📱 平台: {args.platform}")
    print(f"⏰ 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 设置环境变量
    if args.platform:
        os.environ["TEST_PLATFORM"] = args.platform
    if args.device:
        os.environ["TEST_DEVICE"] = args.device
    if args.app_path:
        os.environ["TEST_APP_PATH"] = args.app_path
    
    success = True
    
    if args.action == "install":
        success = install_dependencies()
    
    elif args.action == "check":
        success = check_appium_server()
    
    elif args.action == "start-server":
        success = start_appium_server()
    
    elif args.action == "smoke":
        success = run_smoke_tests(args.platform)
    
    elif args.action == "functional":
        success = run_functional_tests(args.platform)
    
    elif args.action == "ui":
        success = run_ui_tests(args.platform)
    
    elif args.action == "all":
        success = run_all_tests(args.platform)
    
    elif args.action == "parallel":
        success = run_parallel_tests(args.platform, args.workers)
    
    elif args.action == "allure":
        success = generate_allure_report()
    
    elif args.action == "open-report":
        success = open_allure_report()
    
    elif args.action == "clean":
        success = clean_reports()
    
    # 显示结果
    print(f"\n{'='*50}")
    if success:
        print("🎉 操作执行成功!")
    else:
        print("💥 操作执行失败!")
    print(f"{'='*50}")
    
    return 0 if success else 1


if __name__ == "__main__":
    sys.exit(main()) 